package com.af.community.smart.business

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.af.community.smart.base.*
import com.af.community.smart.model.CityData
import com.af.community.smart.model.PeopleData
import com.af.community.smart.share.Const
import com.af.community.smart.utils.*
import com.af.community.smart.utils.DialogHelper.showCityDialog
import com.af.community.smart.utils.DialogHelper.showDateDialog
import com.af.community.smart.utils.DialogHelper.showItemDialog
import com.af.community.smart.utils.DialogHelper.showListDialog
import com.af.community.smart.viewmodel.PeopleViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.matisse.Matisse
import com.lxj.matisse.MimeType
import com.sunfusheng.GlideImageView
import kotlinx.android.synthetic.main.fragment_people_second.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.toast
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel
import java.util.*
import kotlin.collections.ArrayList

class PeopleEditSecondActivity : BaseActivity() {

    private var mGridId = ""    //网格id
    private var mSex = ""       //性别
    private var mNation = ""    //民族
    private var mhType = ""     //户口类型
    private var mIn = ""        //流入时间
    private var nzType = ""     //住房类型
    private var nPlace = ""     //籍贯
    private var nBirth = ""     //出生日期
    private var nAvatar = ""    //上传图片
    private var nCulture = ""   //文化程度
    private var nRelation = ""  //户主关系
    private var nLevel = ""     //职称等级
    private var nReason = ""    //居住事由
    private var nState = ""     //登记证
    private var nTime = ""      //登记日期
    private var nEnd = ""       //到期日期
    private var nCan = ""       //是否残疾
    private var nDi = ""        //是否低保
    private var nShi = ""       //是否实业
    private var nProve = ""     //上传证明

    private val list = ArrayList<String>()
    private val cityList = ArrayList<CityData>()
    private lateinit var mData: PeopleData

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_people_second)
        initTitle(title = "详情", name = "保存")

        mData = intent.getSerializableExtra("data") as PeopleData

        mGridId = mData.gridId.orEmpty()
        mSex = mData.sex.orEmpty()
        mNation = mData.national.orEmpty()
        mhType = mData.residenceType.orEmpty()
        mIn = mData.intotime.toFormatString(eFormat = "yyyy-MM-dd")
        nzType = mData.housType.orEmpty()
        nPlace = mData.birthplace.orEmpty()
        nBirth = mData.birthday.orEmpty()
        nAvatar = mData.avatar
            .orEmpty()
            .trimEnd(',')
        nCulture = mData.education.orEmpty()
        nRelation = mData.relation.orEmpty()
        nLevel = mData.titleLevel.orEmpty()
        nReason = mData.toLiveFor.orEmpty()
        nState = mData.temporaryResidence.orEmpty()
        nTime = mData.temporarySignTime.toFormatString(eFormat = "yyyy-MM-dd")
        nEnd = mData.temporaryEndTime.toFormatString(eFormat = "yyyy-MM-dd")
        nProve = mData.prove
            .orEmpty()
            .replace(";", ",")
            .trimEnd(',')

        people_grid.text = mData.gridName
        people_znum.setText(mData.housNumber)
        people_hnum.setText(mData.doorNumber)
        people_name.setText(mData.userName)
        people_sex.text = when (mSex) {
            "0" -> "女"
            "1" -> "男"
            else -> ""
        }
        people_nation.text = mNation
        people_id.setText(mData.account)
        people_type.text = mhType
        people_in.text = mIn
        people_znum.setSelection(people_znum.text.length)
        people_hnum.setSelection(people_hnum.text.length)
        people_name.isEnabled = false //不可编辑
        people_id.isEnabled = false   //不可编辑

        people_ztype.text = nzType
        people_mname.setText(mData.owner)
        people_mid.setText(mData.ownerID)
        people_lnum.setText(mData.zoneNumber)
        people_place.text = nPlace
        people_birth.text = nBirth
        peopoe_img.loadRoundedImage(nAvatar.scaleImage())
        people_culture.text = nCulture
        people_relation.text = nRelation
        people_level.text = nLevel
        people_reason.text = nReason
        people_state.text = nState
        people_time1.text = nTime
        people_time2.text = nEnd
        people_tel1.setText(mData.phone)
        people_addr1.setText(mData.address)
        people_job.setText(mData.professional)
        people_unit.setText(mData.workName)
        people_addr2.setText(mData.workAddress)
        people_tel2.setText(mData.workTel)
        people_memo.setText(mData.remark)

        people_mname.setSelection(people_mname.text.length)
        people_mid.setSelection(people_mid.text.length)
        people_lnum.setSelection(people_lnum.text.length)
        if (mIn.isNotEmpty()) mIn += " 00:00:00"
        if (nTime.isNotEmpty()) nTime += " 00:00:00"
        if (nEnd.isNotEmpty()) nEnd += " 00:00:00"

        people_can.text = "否"
        people_di.text = "否"
        people_shi.text = "否"
        val specialType = mData.specialType ?: ""
        if ("201" in specialType) {
            nCan = "201"
            people_can.text = "是"
        }

        if ("202" in specialType) {
            nDi = "202"
            people_di.text = "是"
        }

        if ("205" in specialType) {
            nShi = "205"
            people_shi.text = "是"
        }

        if (nProve.isEmpty()) {
            mAdapter.updateData(list.apply { add("") })
        } else {
            list.addAll(nProve.split(","))
            if (list.size < 3) list.add(0, "")
            mAdapter.updateData(list)
        }
    }

    override fun getViewModel() = getViewModel<PeopleViewModel>()

    override fun initTitle(title: String, name: String) {
        super.initTitle(title, name)
        bt_sure.gone()
        img_list.apply {
            layoutManager = LinearLayoutManager(
                baseContext,
                LinearLayoutManager.HORIZONTAL,
                true
            )
        }

        //上传证明
        mAdapter = SlimAdapter.create()
            .register<String>(R.layout.item_people_img) { data, injector ->

                val index = list.indexOf(data)

                injector.visibility(
                    R.id.item_people_del,
                    if (data.isEmpty()) View.INVISIBLE else View.VISIBLE
                )
                    .with<GlideImageView>(R.id.item_people) {
                        if (data.isEmpty()) it.loadDrawable(R.mipmap.icon_upload)
                        else it.loadRoundedImage(data.scaleImage())
                    }
                    .clicked(R.id.item_people) {
                        if (data.isEmpty()) {
                            val selectSize = list.filter { it.isNotEmpty() }.size

                            Matisse.from(baseContext)
                                .choose(MimeType.ofImage())
                                .theme(R.style.Matisse_Blue)
                                .capture(true)
                                .originalEnable(false)
                                .maxSelectable(3 - selectSize)
                                .forResult(42)
                        } else {
                            mPosition = index
                            Matisse.from(baseContext)
                                .choose(MimeType.ofImage())
                                .theme(R.style.Matisse_Blue)
                                .capture(true)
                                .originalEnable(false)
                                .maxSelectable(1)
                                .forResult(62)
                        }
                    }
                    .clicked(R.id.item_people_del) {
                        list.remove(data)
                        mAdapter.notifyItemRemoved(index)
                        mAdapter.notifyItemRangeChanged(index, list.size - index)
                        if ("" !in list) {
                            list.add(0, "")
                            mAdapter.notifyItemInserted(0)
                            mAdapter.notifyItemRangeChanged(0, list.size)
                        }
                    }
            }
            .attachTo(img_list)

        //民族
        people_nation_ll.oneClick {
            showItemDialog(
                "请选择民族",
                Const.nationList.indexOf(mNation),
                Const.nationList
            ) { _, hint ->
                mNation = hint
                people_nation.text = hint
            }
        }

        //户口类型
        people_type_ll.oneClick {
            showItemDialog(
                "请选择户口类型",
                Const.typeList.indexOf(mhType),
                Const.typeList
            ) { _, hint ->
                mhType = hint
                people_type.text = hint
            }
        }

        //流入时间
        people_in_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            showDateDialog(
                maxYearValue = yearNow,
                count = 3,
                title = "请选择流入时间",
                isAfterLimited = true,
                callback = { _, _, _, _, _, hint ->
                    mIn = "$hint 00:00:00"
                    people_in.text = hint
                }
            )
        }

        //住房类型
        people_ztype_ll.oneClick {
            showListDialog(
                "集体生活住房", "集体房", "出租房",
                "闲置房", "生产经营房", "其他"
            ) { _, hint ->
                nzType = hint
                people_ztype.text = hint
            }
        }

        //籍贯
        people_place_ll.oneClick {
            if (cityList.isEmpty()) {
                getViewModel().getCityData(this)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribe {
                        cityList.addItems(it)
                        if (cityList.isNotEmpty()) {
                            showCityDialog(
                                title = "请选择籍贯",
                                list = cityList,
                                listener = { province, city, area, _, _, _ ->
                                    nPlace = "$province $city $area"
                                    people_place.text = nPlace
                                }
                            )
                        }
                    }
            } else {
                showCityDialog(
                    title = "请选择籍贯",
                    list = cityList,
                    listener = { province, city, area, _, _, _ ->
                        nPlace = "$province $city $area"
                        people_place.text = nPlace
                    }
                )
            }
        }

        //出生日期
        people_birth_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            showDateDialog(
                maxYearValue = yearNow,
                count = 3,
                title = "请选择出生日期",
                isAfterLimited = true,
                callback = { _, _, _, _, _, hint ->
                    nBirth = hint
                    people_birth.text = hint
                }
            )
        }

        //上传图片
        peopoe_img.oneClick {
            Matisse.from(baseContext)
                .choose(MimeType.ofImage())
                .theme(R.style.Matisse_Blue)
                .capture(true)
                .originalEnable(false)
                .maxSelectable(1)
                .forResult(52)
        }

        //文化程度
        people_culture_ll.oneClick {
            showListDialog(
                "文盲", "小学", "初中", "高中", "中专",
                "大专", "本科", "研究生", "博士"
            ) { _, hint ->
                nCulture = hint
                people_culture.text = hint
            }
        }

        //户主关系
        people_relation_ll.oneClick {
            showItemDialog(
                "请选择与户主关系",
                Const.relationList.indexOf(nRelation),
                Const.relationList
            ) { _, hint ->
                nRelation = hint
                people_relation.text = hint
            }
        }

        //职称等级
        people_level_ll.oneClick {
            showListDialog(
                "高级", "中级", "初级", "高级技师", "技师",
                "高级工", "中级工", "初级工", "无等级"
            ) { _, hint ->
                nLevel = hint
                people_level.text = hint
            }
        }

        //居住事由
        people_reason_ll.oneClick {
            showListDialog(
                "务工", "务农", "经商", "盲流", "其他"
            ) { _, hint ->
                nReason = hint
                people_reason.text = hint
            }
        }

        //登记情况
        people_state_ll.oneClick {
            showListDialog(
                "登记类", "临时居住证", "居住证"
            ) { _, hint ->
                nState = hint
                people_state.text = hint
            }
        }

        //登记日期
        people_time1_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            showDateDialog(
                maxYearValue = yearNow,
                count = 3,
                title = "请选择登记日期",
                isAfterLimited = true,
                callback = { _, _, _, _, _, hint ->
                    nTime = "$hint 00:00:00"
                    people_time1.text = hint
                }
            )
        }

        //到期日期
        people_time2_ll.oneClick {
            val calendar = Calendar.getInstance()
            val yearNow = calendar.get(Calendar.YEAR)
            showDateDialog(
                minYearValue = yearNow,
                count = 3,
                title = "请选择预计到期日期",
                isBeforeLimited = true,
                callback = { _, _, _, _, _, hint ->
                    nEnd = "$hint 00:00:00"
                    people_time2.text = hint
                }
            )
        }

        //是否残疾
        people_can_ll.oneClick {
            showListDialog(
                "是", "否"
            ) { index, hint ->
                nCan = if (index == 0) "201" else ""
                people_can.text = hint
            }
        }

        //是否低保
        people_di_ll.oneClick {
            showListDialog(
                "是", "否"
            ) { index, hint ->
                nDi = if (index == 0) "202" else ""
                people_di.text = hint
            }
        }

        //是否失业
        people_shi_ll.oneClick {
            showListDialog(
                "是", "否"
            ) { index, hint ->
                nShi = if (index == 0) "205" else ""
                people_shi.text = hint
            }
        }

        tvRight?.oneClick {
            when {
                people_znum.text.isBlank() -> {
                    people_znum.requestFocus()
                    toast("请输入住房编号")
                    return@oneClick
                }
                people_hnum.text.isBlank() -> {
                    people_hnum.requestFocus()
                    toast("请输入户口编号")
                    return@oneClick
                }
                people_tel1.text.isEmpty() -> {
                    people_tel1.requestFocus()
                    showToast("请输入联系手机")
                    return@oneClick
                }
                !people_tel1.textString().isMobile() -> {
                    people_tel1.requestFocus()
                    showToast("请输入正确的联系手机")
                    return@oneClick
                }
                people_mid.text.isNotEmpty()
                        && !CommonUtil.IDCardValidate(people_mid.textString()) -> {
                    people_mid.requestFocus()
                    toast("请输入正确的房主身份证号")
                    return@oneClick
                }
                people_tel2.text.isNotEmpty()
                        && !people_tel2.textString().isTel() -> {
                    people_tel2.requestFocus()
                    showToast("请输入正确的单位电话")
                    return@oneClick
                }
            }

            val specialList = ArrayList<String>()
            if (nCan.isNotEmpty()) specialList.add(nCan)
            if (nDi.isNotEmpty()) specialList.add(nDi)
            if (nShi.isNotEmpty()) specialList.add(nShi)

            getViewModel().getAddData(
                "id" to mData.id.orEmpty(),
                "baseType" to mData.baseType.orEmpty(),
                "gridId" to mGridId,
                "gridName" to people_grid.textString(),
                "housNumber" to people_znum.trimString(),
                "doorNumber" to people_hnum.trimString(),
                "userName" to people_name.trimString(),
                "sex" to mSex,
                "national" to mNation,
                "account" to people_id.textString(),
                "residenceType" to mhType,
                "intotime" to mIn,
                "phone" to people_tel1.textString(),

                "housType" to nzType,
                "owner" to people_mname.trimString(),
                "ownerID" to people_mid.textString(),
                "zoneNumber" to people_lnum.trimString(),
                "birthplace" to nPlace,
                "birthday" to nBirth,
                "avatar" to nAvatar,
                "education" to nCulture,
                "relation" to nRelation,
                "titleLevel" to nLevel,
                "toLiveFor" to nReason,
                "temporaryResidence" to nState,
                "temporarySignTime" to nTime,
                "temporaryEndTime" to nEnd,
                "address" to people_addr1.trimString(),
                "professional" to people_job.trimString(),
                "workName" to people_unit.trimString(),
                "workAddress" to people_addr2.trimString(),
                "workTel" to people_tel2.textString(),
                "specialType" to specialList.joinToString(","),
                "prove" to nProve,
                "remark" to people_memo.trimString()
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        val obj = JSONObject(it)

                        mData.apply {
                            gridId = mGridId
                            gridName = people_grid.textString()
                            housNumber = people_znum.trimString()
                            doorNumber = people_hnum.trimString()
                            userName = people_name.trimString()
                            sex = mSex
                            national = mNation
                            account = people_id.textString()
                            residenceType = mhType
                            intotime = obj.optString("intotime")

                            housType = nzType
                            owner = people_mname.trimString()
                            ownerID = people_mid.textString()
                            zoneNumber = people_lnum.trimString()
                            birthplace = nPlace
                            birthday = nBirth
                            avatar = nAvatar
                            education = nCulture
                            relation = nRelation
                            titleLevel = nLevel
                            toLiveFor = nReason
                            temporaryResidence = nState
                            temporarySignTime = obj.optNotNull("temporarySignTime")
                            temporaryEndTime = obj.optNotNull("temporaryEndTime")
                            phone = people_tel1.textString()
                            address = people_addr1.trimString()
                            professional = people_job.trimString()
                            workName = people_unit.trimString()
                            workAddress = people_addr2.trimString()
                            workTel = people_tel2.textString()
                            specialType = specialList.joinToString(",")
                            prove = nProve
                            remark = people_memo.trimString()
                        }
                        LiveEventBus.get("peopie_edit").post(mData)
                        LiveEventBus.get("people_check").post("done")
                        ActivityStack.screenManager.popActivities(this@PeopleEditSecondActivity::class.java)
                    }
                )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                42, 62 -> {
                    val imgSelect = ArrayList<String>()
                    val imgList = Matisse.obtainSelectPathResult(data)
                    val imgCapture = Matisse.obtainCaptureImageResult(data)

                    when {
                        !imgList.isNullOrEmpty() -> imgSelect.addAll(imgList)
                        imgCapture != null -> imgSelect.add(imgCapture)
                    }

                    if (imgSelect.isNotEmpty()) {
                        OSSHelper.manager.uploadImages(
                            pathList = imgSelect,
                            onBefore = { showLoading() },
                            onAfter = { dismissLoading() },
                            onSuccess = { _, result ->
                                if (result != null) {
                                    val img = result.responseHeader["url"].orEmpty()
                                    if (img.isNotEmpty()) {
                                        if (requestCode == 42) {
                                            list.remove("")
                                            list.add(0, img)
                                            nProve = list.joinToString(",")
                                            if (list.size < 3) list.add(0, "")
                                            mAdapter.notifyDataSetChanged()
                                        } else {
                                            list.removeAt(mPosition)
                                            list.add(mPosition, img)
                                            nProve =
                                                list.filter { it.isNotEmpty() }.joinToString(",")
                                            mAdapter.notifyDataSetChanged()
                                        }
                                    }
                                }
                            },
                            OnError = { index, _ -> if (index < 0) toast("网络异常，请稍候再试！") }
                        )
                    }
                }
                52 -> {
                    val imgList = Matisse.obtainSelectPathResult(data)
                    val imgCapture = Matisse.obtainCaptureImageResult(data)
                    val imgSelect = when {
                        !imgList.isNullOrEmpty() -> imgList[0]
                        imgCapture != null -> imgCapture
                        else -> ""
                    }
                    if (imgSelect.isNotEmpty()) {
                        OSSHelper.manager.uploadImage(
                            path = imgSelect,
                            onBefore = { showLoading() },
                            onAfter = { dismissLoading() },
                            onSuccess = {
                                val img = it.responseHeader["url"].orEmpty()
                                if (img.isNotEmpty()) {
                                    nAvatar = img
                                    peopoe_img.loadRoundedImage(img.scaleImage())
                                }
                            },
                            OnError = { toast("网络异常，请稍候再试！") }
                        )
                    }
                }
            }
        }
    }

}
